﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Collections;
using System.Text.RegularExpressions;

namespace AlphaSolutionsGP
{
    public partial class frmModuleView : Form
    {
        Module aModule;
        bool isModify;
        string modulecode;
        ArrayList staffIds = new ArrayList();

         int totalWeighting = 100;
         int weightingLeft = 0;

        

        public frmModuleView()
        {
            InitializeComponent();
            isModify = false;
            fillInCombo(cmbCourse, "course_Code", "COURSE");
            fillInCombo(cmbStaffId, "staff_ID", "STAFF");
        }

        public frmModuleView(Module m)
        {
            
            InitializeComponent();
            //add an extra item to the course code combo for the not assigne course code
            cmbCourse.Items.Add("Not assigned");
            fillInCombo(cmbCourse, "course_Code", "COURSE");
            fillInCombo(cmbStaffId, "staff_ID", "STAFF");
            isModify = true;
            aModule = m;
            txtTitle.Text = m.Title;
            cmbCourse.Text = m.CourseCode;
            txtYear.Text = m.Level.ToString();
            txtCredits.Text = m.Credits.ToString();
            txtModuleCode.Text = m.ModuleCode;
            cmbStaffId.SelectedItem = m.StaffID;
            modulecode = m.ModuleCode;
            txtDescription.Text = m.Description;
            txtDepartment.Text = m.Field;
            displayAssessment(m.ModuleCode.ToString());

            //set the add and refreash assessment buttons to be visible
            btnAddAssessment.Visible = true;
            btnRefreshAssessment.Visible = true;
     
        }

        private void frmModuleView_Load(object sender, EventArgs e)
        {
            
        }

        //validate the fields of the module form
        private bool validate()
        {
            bool flag = true;
            string msg = "";

            if (txtTitle.Text == "")
            {
                msg += "\n- Title must not be blank.";
                flag = false;
            }
            Match matchModuleCode = Regex.Match(txtModuleCode.Text.Trim(), @"^[a-zA-Z][0-9][0-9][0-9][0-9]"); //check for integer numbers only within the string 
            if (!matchModuleCode.Success || txtModuleCode.Text == "" || txtModuleCode.Text.Length != 5) //if no characters were found
            {
                msg += "\n- Module code is blank or invalid. (LNNNN)";
                flag = false;
            }
            if (txtDepartment.Text == "")
            {
                msg += "\n- You must choose or enter a department for the module";
                flag = false;
            }
            /*if (cmbCourse.SelectedIndex<0)
            {
                msg += "\n- You must select a course to assign this module to";
                flag = false;
            }*/
            if (cmbStaffId.SelectedIndex < 0)
            {
                msg += "\n- You must select a Module Leader for the course";
                flag = false;
            }
            if (txtDescription.Text == "")
            {
                msg += "\n- You must enter a description for the module, you can include information such as:\n 1. what types of assessments are used in the module";
                flag = false;
            }
            if(!flag)
                MessageBox.Show(msg, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            return flag;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (validate())
            {
                if (isModify == false)
                {
                    Module aModule = new Module();
                    aModule.ModuleCode = txtModuleCode.Text;
                    aModule.CourseCode = cmbCourse.Text;
                    aModule.Title = txtTitle.Text;
                    aModule.Field = txtDepartment.Text;
                    aModule.Level = int.Parse(txtYear.Text);
                    aModule.Description = txtDescription.Text;
                    aModule.Credits = int.Parse(txtCredits.Text);
                    aModule.StaffID = cmbStaffId.Text;
                    aModule.createModule();
                    MessageBox.Show("Module created");
                }
                else if (isModify == true)
                {
                    Module editModule = new Module();
                    editModule.ModuleCode = txtModuleCode.Text;
                    editModule.CourseCode = cmbCourse.Text;
                    editModule.Title = txtTitle.Text;
                    editModule.Field = txtDepartment.Text;
                    editModule.Level = int.Parse(txtYear.Text);
                    editModule.Description = txtDescription.Text;
                    editModule.Credits = int.Parse(txtCredits.Text);
                    editModule.StaffID = cmbStaffId.Text;
                    editModule.ammendModule(modulecode);
                    MessageBox.Show("Changes have been saved");

                }
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void displayAssessment(string moduleID)
        {
            alpha_dbStudentDataSet.ASSESSMENT.Clear();
            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Connection failed");
            }
            try
            {
                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT * FROM ASSESSMENT WHERE MODULE_module_Code='" + moduleID + "'";
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                da.Fill(this.alpha_dbStudentDataSet.ASSESSMENT);
                da.Dispose();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to fill table due to the following error:\n\n" + ex.ToString());
            }
            finally
            {
                connection.Close();

            }
        }

        private void fillInCombo(ComboBox cb, string column, string table)
        {
            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT DISTINCT " + column + " FROM " + table + ""; //select the biggest staff id
                MySqlDataReader myReader = cmd.ExecuteReader();
                string nameColumn = "" + column + "";
                while (myReader.Read())
                {
                    column = myReader.GetString(nameColumn);
                    cb.Items.Add(column);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to fill table due to the following error:\n\n" + ex.ToString());
            }

            finally
            {
                connection.Close();

            }
        }

        //code to find staff ID from name search
        //this method will search for IDs into the student tab given the first name and surname
        private void findIDByName(string firstName, string surname)
        {
            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
                MySqlCommand cmd = connection.CreateCommand();
                MySqlDataReader myReader;
                string tempID = "";
                if (surname.Equals("") && !firstName.Equals("")) //if only firstaname is filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_name LIKE '" + firstName + "%' ORDER BY ID"; //select student/staff id for the given first name

                }
                else if (!surname.Equals("") && firstName.Equals("")) //if only surname is filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_surname LIKE '" + surname + "%' ORDER BY ID"; //select student/staff id for the given surname
                }
                else //if firstaname and surname are filled in
                {
                    cmd.CommandText = "SELECT ID FROM PERSON WHERE person_name LIKE '" + firstName + "%' && person_surname LIKE '" + surname + "%' ORDER BY ID"; //select student id for the given surname
                }
                myReader = cmd.ExecuteReader(); //execute the reader
                while (myReader.Read())
                {
                    tempID = myReader.GetString("ID");
                    if (tempID.StartsWith("9"))
                    {
                        staffIds.Add(myReader.GetString("ID")); // add the id to the arrylist
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to fill table due to the following error:\n\n" + ex.ToString()); //failure message
            }

            finally
            {
                connection.Close(); //close the connection

            }

        }

        //this method will take what is in the array list of staff IDs and put them into the combo box
        private void fillInComboIDStaff()
        {
            for (int i = 0; i < staffIds.Count; i++)
            {
                cmbStaffId.Items.Add(staffIds[i].ToString());
            }
        }

        //this is used when the text is changed in the search
        private void clearStaffIDs()
        {
            //clear the staff arraylist
            for (int i = 0; i < staffIds.Count; i++)
            {
                staffIds.RemoveAt(i);
            }
        }

        private void cmbStaffId_Leave(object sender, EventArgs e)
        {
            clearStaffIDs();
            txtStaffIDSearch.Text = "";
        }

        private void txtStaffIDSearch_Leave(object sender, EventArgs e)
        {
            string[] name = txtStaffIDSearch.Text.Split(' ');
            string firstName = name[0]; // store the firstname
            string surname;
            if (name.Length > 1)
                surname = name[1];
            else surname = "";

            clearStaffIDs();
            this.cmbStaffId.Items.Clear();//clear staff combo
            findIDByName(firstName, surname); //find all the IDs that matches among the records
            fillInComboIDStaff(); // add the arraylist into the combo
            clearStaffIDs(); //clear staff array lists
        }

        private void btnHelpStaffId_Click(object sender, EventArgs e)
        {
            MessageBox.Show("To assign a tutor simply type their name in the text box above and choose their ID from the dropdown list.", "Staff ID Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void txtModuleCode_Leave(object sender, EventArgs e)
        {
            string txt = txtModuleCode.Text;
            txtModuleCode.Text = "";
            txtModuleCode.Text = txt.ToUpper();
        }

        private void aSSESSMENTDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex > 1) return;
                
                int assessment_ID = int.Parse(aSSESSMENTDataGridView[2, e.RowIndex].Value.ToString());
                string module_Code = (string)aSSESSMENTDataGridView[3, e.RowIndex].Value;
                string status = (string)aSSESSMENTDataGridView[4, e.RowIndex].Value;
                DateTime hand_out_date = (DateTime)aSSESSMENTDataGridView[5, e.RowIndex].Value;
                DateTime due_in_date = (DateTime)aSSESSMENTDataGridView[6, e.RowIndex].Value;
                int weighting = int.Parse(aSSESSMENTDataGridView[7, e.RowIndex].Value.ToString());
                string type = (string)aSSESSMENTDataGridView[8, e.RowIndex].Value;
                string description = (string)aSSESSMENTDataGridView[9, e.RowIndex].Value;
                Assesment theAssessment = new Assesment(assessment_ID, module_Code, status, hand_out_date.ToString(), due_in_date.ToString(), weighting, type, description);

                if (e.ColumnIndex == 0)
                {
                    //view
                    frmAssessmentView f = new frmAssessmentView(theAssessment);
                    f.Show();
                }
                else if (e.ColumnIndex == 1)
                {
                    //delete
                    if (MessageBox.Show(this, "Are you sure you wish to delete this assessment", "Deleting assessment...",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        == DialogResult.Yes)
                    {
                        theAssessment.removeAssessment();
                    }
                }
            }
            catch (Exception ex)
            {
                //do nothing
                MessageBox.Show(ex.ToString());
            }

        }

        //create new instance of event form with blank constructor
        //private void bntCreateNew_Click(object sender, EventArgs e)
        //{
        //    frmAssessmentView assessmentForm = new frmAssessmentView();
        //    assessmentForm.Show();
        //}

        private void btnAddAssessment_Click(object sender, EventArgs e)
        {
            //calculate the percentage left after the form loads
            weightingLeft = totalWeighting - calculateWeightingPercentageLeft(7);
            if (weightingLeft == 0)
            {
                MessageBox.Show("No more assessments can be created for this module \nas the limit weighting percentage has been reached.");
            }
            else
            {
                frmAssessmentView assessmentForm = new frmAssessmentView(txtModuleCode.Text, weightingLeft);
                assessmentForm.Show();
            }
        }

        private void refresh_Click(object sender, EventArgs e)
        {
            //displayQualification(aStudent.ID.ToString()); 
            displayAssessment(aModule.ModuleCode.ToString());
        }

        //get all the values summed up from a specific cell
        private int calculateWeightingPercentageLeft(int columnNumber)
        {
            //count the rows in the ASSESSMENT table
            int rowCount = this.aSSESSMENTDataGridView.Rows.Count;
            int cellVAlue = 0;
            for (int i = 0; i < rowCount; i++ )
            {
                //summ up all the values which are in the cell number specified
                cellVAlue += (int)aSSESSMENTDataGridView.Rows[i].Cells[columnNumber].Value;
            }
            return cellVAlue;
        }

    }
}
